/**
 * @file server.dev.js
 * @author lavas
 */

var LavasCore = require("lavas-core-vue");
var express = require("express");
var stoppable = require("stoppable");
var proxy = require("http-proxy-middleware");
var bodyParser = require("body-parser");
var history = require('connect-history-api-fallback');

var configPath = "./lavas.config.js";
// fix https://github.com/lavas-project/lavas/issues/50
if (process.argv.length >= 3 && process.argv[2] !== "dev") {
    configPath = process.argv[2];
}

/**
 * API Proxy Configuration
 *
 * @see https://github.com/chimurai/http-proxy-middleware
 * @type {Object}
 */
var proxyTable = {
    // proxy table example
    // '/api': {
    //     target: 'https://lavas.baidu.com',
    //     changeOrigin: true
    // }
};

var port = process.env.PORT || 3333;
var core = new LavasCore(__dirname);
var app;
var server;

/**
 * start dev server
 */
function startDevServer() {
    app = express();
    app.use(history());
    // parse application/x-www-form-urlencoded
    app.use(bodyParser.urlencoded({ extended: false }));

    // parse application/json
    app.use(bodyParser.json());

    core.build()
        .then(function() {
            // API Proxying during development
            Object.keys(proxyTable).forEach(function(pattern) {
                app.use(pattern, proxy(proxyTable[pattern]));
            });

            const chatServer = require("./chat-server");
            chatServer.makeTokenMap();
            chatServer.checkToken(app);
            app.use("/room", require("./chat-server/routes/room"));
            app.use("/user", require("./chat-server/routes/user"));
            app.use("/file", require("./chat-server/routes/files"));
            chatServer.httpsServer(app);
            chatServer.wsServer(app);
            chatServer.connectWithWs(app);

            app.use(core.expressMiddleware());

            /**
             * server.close() only stop accepting new connections,
             * we need to close existing connections with help of stoppable
             */
            server = stoppable(
                app.listen(port, function() {
                    console.log("server started at http://localhost:" + port);
                })
            );
        })
        .catch(function(err) {
            console.log(err);
        });
}

/**
 * every time lavas rebuild, stop current server first and restart
 */
core.on("rebuild", function() {
    core.close().then(function() {
        server.stop();
        startDevServer();
    });
});

core.init(process.env.NODE_ENV || "development", true, { configPath }).then(
    function() {
        startDevServer();
    }
);

// catch promise error
process.on("unhandledRejection", function(err) {
    console.warn(err);
});
